package com.echo.register.service;

import com.alibaba.fastjson.JSON;
import com.echo.register.commons.Constants;
import com.echo.register.commons.proto.LoginReq;
import com.echo.register.commons.proto.LoginResp;
import com.echo.register.commons.redis.RecordsKey;
import com.echo.register.commons.redis.RedisClient;
import com.echo.register.commons.result.RetCode;
import com.echo.register.commons.utils.CommonUtils;
import com.echo.register.commons.utils.ObjectUtils;
import com.echo.register.domain.VoteRecords;
import com.echo.register.mapper.RecordsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @program: com.echo.voter
 * @description: 登录serivce
 * @author: Xiaoti
 * @create: 2018-11-05 14:45
 **/
@Service
public class LoginService {

    private static Logger logger = LoggerFactory.getLogger(LoginService.class);

    @Resource
    RedisClient redisClient;
    @Resource
    RecordsMapper recordsMapper;

    private static String COOKIE_UM_TOKEN = "um_token";

    public LoginResp loginRecord(HttpServletRequest request, HttpServletResponse response, LoginReq loginReq){
        LoginResp loginResp = new LoginResp();
        String ip = CommonUtils.getIpAddress(request);
        if(ip == null || ip.equals(Constants.EMPTY)){
            loginResp.setFlag(RetCode.FAIL);
            loginResp.setMsg("IP地址为空");
            return loginResp;
        }

        String umId = loginReq.getUmId();
        VoteRecords records = getRecords(umId);
        //判断数据库获取的对象是否为空
        if(ObjectUtils.isNotNullOrEmpty(records)){
            //判断um号是否与Ip一致
            if(!records.getUmIp().equals(ip)){
                HttpSession session = request.getSession();
                session.setAttribute("records", records);
//                loginResp.setFlag(RetCode.FAIL);
//                loginResp.setMsg("UM号与第一次登录的IP地址不一致！");
//                logger.info("um id is diffrent with first bind ip!");
                loginResp.setFlag(RetCode.SUCCESS);
                return loginResp;
            }
        }else{
            records = recordsMapper.getRecordsByIp(ip);
            if(ObjectUtils.isNotNullOrEmpty(records)){
//                loginResp.setFlag(RetCode.FAIL);
//                loginResp.setMsg("IP地址已被占用！");
//                logger.info("The Ip address was be used!");
                HttpSession session = request.getSession();
                session.setAttribute("records", records);
                return loginResp;
            }
            records = new VoteRecords();
            records.setUmId(umId);
            records.setUmIp(ip);
            records.setVoteCount(0);
            records.setCreatedTime(new Date());
            records.setUpdatedTime(new Date());
            records.setRecordsFwmy(0);
            records.setRecordsAqws(0);
            records.setRecordsKjcx(0);
            records.setRecordsKjxr(0);
            records.setRecordsSjxf(0);
            records.setRecordsZyyy(0);
            recordsMapper.insertRecords(records);
        }
//        CommonUtils.addCookie(response, umId, ip, COOKIE_UM_TOKEN);
        loginResp.setFlag(RetCode.SUCCESS);
        redisClient.setexObjec(umId, records, RecordsKey.TOKEN_EXPIRE);
        redisClient.setexObjec(ip, records, RecordsKey.TOKEN_EXPIRE);
        return loginResp;
    }

    private VoteRecords getRecords(String umId){
        //先从缓存中获取
        VoteRecords records = redisClient.getObject(VoteRecords.class, umId);
        logger.info("get from redis, records: {}", JSON.toJSON(records));
        //判断对象是否为空
        if(!ObjectUtils.isNotNullOrEmpty(records)){
            records = recordsMapper.getRecordsByUmId(umId);
            logger.info("get from datebase, records: {}", JSON.toJSON(records));
        }
        return records;
    }
}
